package cn.sdormitory.job.dormitory;

import cn.sdormitory.attendance.dao.HolidayConfigDao;
import cn.sdormitory.attendance.entity.HolidayConfig;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.dto.StudentDept;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.smartdor.dao.SdWeekendAttenceDao;
import cn.sdormitory.smartdor.entity.SdWeekendAttence;
import cn.sdormitory.sys.dao.SysConfigDao;
import cn.sdormitory.sys.entity.SysConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.ListUtils;
import org.apache.http.client.utils.DateUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @className: WeekendNotClockInDataJob
 * @author: Alex
 * @date: 2024/9/14
 **/
public class WeekendNotClockInDataJob extends QuartzJobBean {
	
	@Autowired
	private SdWeekendAttenceDao sdWeekendAttenceDao;
	
	@Autowired
	private BStudentDao bStudentDao;
	
	@Autowired
	private HolidayConfigDao holidayConfigDao;
	
//	@Resource
//	private StudentTrajectoryDao studentTrajectoryDao;
	
	@Resource
	private SysConfigDao sysConfigDao;
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		Date date = new Date();
		String accessDate = DateUtils.formatDate(date, "yyyy-MM-dd");

//		String startDate = accessDate + " 17:30:00";
//		String endDate = accessDate + " 18:30:00";
		
		//查询所有住宿学生
		LambdaQueryWrapper<BStudent> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BStudent::getStatus,"1");
		List<BStudent> allStudent = bStudentDao.selectList(wrapper);
		
		List<SdWeekendAttence> clockInRecords = sdWeekendAttenceDao.getWeekendClockInData(accessDate);
		
		List<HolidayConfig> holiday = holidayConfigDao.getHolidayByDate(accessDate);
		
		// 如果没有添加假期数据
		if (holiday.isEmpty()) {
			return;
		}
		
		// 如果有假期数据，则根据部门假期配置选取节假日最后一天的考勤数据
		boolean qmxNeedClockIn = false;
		boolean bcspNeedClockIn = false;
		boolean sxNeedClockIn = false;
		// 遍历假期数据，如果部门放假的最后一天是当天，则查看该部门下的学生是否打卡，如果不是当天，则不需要查看该学生的打卡信息。
		for (HolidayConfig holidayConfig : holiday) {
			if (holidayConfig.getDeptId() == 12  && holidayConfig.getHolidayEnd().equals(accessDate)) {
				qmxNeedClockIn = true;
				continue;
			}
			
			if (holidayConfig.getDeptId() == 6 && holidayConfig.getHolidayEnd().equals(accessDate)) {
				bcspNeedClockIn = true;
				continue;
			}
			
			if (holidayConfig.getDeptId() == 7 && holidayConfig.getHolidayEnd().equals(accessDate)) {
				sxNeedClockIn = true;
			}
		}
		
		// 如果都不需要打卡，直接返回。
		if (!sxNeedClockIn && !bcspNeedClockIn && !qmxNeedClockIn) {
			return;
		}
		
		//提交数据列表
		List<SdWeekendAttence> sdAttendanceList = new ArrayList<>();
		
		// 遍历所有学生数据 如果未打卡的就插入数据库
		for(BStudent student : allStudent){

			//如果该学生所在部门放假，则不进行数据插入
			StudentDept studentDept = bStudentDao.getStudentDept(student.getStudentNo());
			
			// 启蒙星
			if (studentDept.getDeptPid() == 12 && !qmxNeedClockIn) {
				continue;
			}
			
			if (studentDept.getDeptPid() == 6 && !bcspNeedClockIn) {
				continue;
			}
			
			if (studentDept.getDeptPid() == 7 && !sxNeedClockIn) {
				continue;
			}
			
			//考勤机上是否存在打卡记录
			boolean isClockIn = clockInRecords.stream().anyMatch(sdWeekendAttence -> sdWeekendAttence.getStudentNo().equals(student.getStudentNo()));
			// 有打卡记录则不再判断数据
			if (isClockIn) {
				continue;
			}
//			// 如果考勤机上面没有打卡记录，则去门禁系统上面查找是否有进入校园记录
//			LambdaQueryWrapper<StudentTrajectory> queryWrapper = new LambdaQueryWrapper<>();
//			queryWrapper.eq(StudentTrajectory::getStudentId, student.getId());
//			queryWrapper.ge(StudentTrajectory::getCreateTime, DateUtil.parse(accessDate + " " + weekendStartTime, "yyyy-MM-dd HH:mm:ss", Locale.CHINA));
//			queryWrapper.le(StudentTrajectory::getCreateTime, DateUtil.parse(accessDate + " " + weekendEndTime, "yyyy-MM-dd HH:mm:ss", Locale.CHINA));
//			queryWrapper.orderByDesc(StudentTrajectory::getCreateTime);
//			List<StudentTrajectory> trajectories = studentTrajectoryDao.selectList(queryWrapper);
//
		
			addStudentAttenceRecord(null,null, accessDate, sdAttendanceList, student, "2", "4");
			
//
//			// 门禁系统上面有出入记录 则获取最后一条数据 如果是进入校园则插入已打卡数据 如果是离开学校，则插入未打卡数据
//			StudentTrajectory studentTrajectory = trajectories.get(0);
//			if (studentTrajectory.getType().equals("1")) {
//				// 到校
//				addStudentAttenceRecord(studentTrajectory.getFaceTime(),studentTrajectory.getDeviceAddr(), accessDate, sdAttendanceList, student, "1", "2");
//				continue;
//			}
//			if (studentTrajectory.getType().equals("2")) {
//				// 离校
//				addStudentAttenceRecord(null, null, accessDate, sdAttendanceList, student, "2", "4");
//			}
		}
		List<List<SdWeekendAttence>> partition = ListUtils.partition(sdAttendanceList, 100);
		for (List<SdWeekendAttence> item : partition) {
			sdWeekendAttenceDao.insertBatch(item);
		}
	}
	
	private void addStudentAttenceRecord(String faceTime,String deviceName, String accessDate, List<SdWeekendAttence> sdAttendanceList, BStudent student, String attenceStatus, String flag) {
		SdWeekendAttence insert = new SdWeekendAttence();
		insert.setDeviceNo(deviceName);
		insert.setStudentNo(student.getStudentNo());
		try {
			insert.setAccessDate(new SimpleDateFormat("yyyy-MM-dd").parse(accessDate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		insert.setAttenceStatus(attenceStatus);
		insert.setBdormitoryId(student.getBdormitoryId());
		insert.setBuildingNo(student.getBuildingNo());
		insert.setStorey(student.getStorey());
		insert.setDormitoryNo(student.getDormitoryNo());
		insert.setFlag(flag);
		if (Objects.nonNull(faceTime)) {
			insert.setCreateTime(DateUtils.parseDate(faceTime));
		}
		sdAttendanceList.add(insert);
	}
	
}
